package cn.kmsoft.common.utils;

import cn.kmsoft.common.unicode.UnicodeInputStream;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpsUtil {
    private static final Log logger = LogFactory.getLog(HttpsUtil.class);


    /**
     * Get请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException {
        HttpGet httpget = new HttpGet(url);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(httpget);

        try {
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            response.close();
            client.close();
        }
    }

    /**
     * Get请求(Basic Authentication)
     *
     * @param url
     * @param user
     * @param password
     * @return
     * @throws IOException
     */
    public static String get(String url, String user, String password) throws IOException {
        HttpGet httpget = new HttpGet(url);
        String header = getBasicAuthenHeader(user, password);
        httpget.setHeader(HttpHeaders.AUTHORIZATION, header);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(httpget);

        try {
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            response.close();
            client.close();
        }
    }

    /**
     * Post请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, String> params) throws IOException {
        HttpPost httppost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            if (params != null) {
                List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
                Iterator<String> iter = params.keySet().iterator();

                if (iter != null) {
                    while (iter.hasNext()) {
                        String key = iter.next();
                        nvpList.add(new BasicNameValuePair(key, params.get(key)));
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvpList, Consts.UTF_8);
                    httppost.setEntity(entity);
                }
            }
            response = client.execute(httppost);
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                response.close();
            }
            client.close();
        }
    }

    /**
     * Post请求(Basic Authentication)
     *
     * @param url
     * @param params
     * @param user
     * @param password
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, String> params, String user, String password) throws IOException {
        String header = getBasicAuthenHeader(user, password);
        HttpPost httppost = new HttpPost(url);
        httppost.setHeader(HttpHeaders.AUTHORIZATION, header);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            if (params != null) {
                List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
                Iterator<String> iter = params.keySet().iterator();

                if (iter != null) {
                    while (iter.hasNext()) {
                        String key = iter.next();
                        nvpList.add(new BasicNameValuePair(key, params.get(key)));
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvpList, Consts.UTF_8);
                    httppost.setEntity(entity);
                }
            }
            response = client.execute(httppost);
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                response.close();
            }
            client.close();
        }
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }

    public static byte[] doGet(String uri) throws IOException {
        HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET");
        return getBytesFromStream(httpsConn.getInputStream());
    }

    public static byte[] doPost(String uri, String data) throws IOException {
        HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "POST");
        setBytesToStream(httpsConn.getOutputStream(), data.getBytes());
        return getBytesFromStream(httpsConn.getInputStream());
    }

    public static HttpsURLConnection getHttpsURLConnection(String uri, String method) throws IOException {
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SSLSocketFactory ssf = ctx.getSocketFactory();

        URL url = new URL(uri);
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setSSLSocketFactory(ssf);
        httpsConn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        httpsConn.setRequestMethod(method);
        httpsConn.setDoInput(true);
        httpsConn.setDoOutput(true);
        return httpsConn;
    }

    private static byte[] getBytesFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] kb = new byte[1024];
        int len;
        while ((len = is.read(kb)) != -1) {
            baos.write(kb, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        baos.close();
        is.close();
        return bytes;
    }

    private static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] kb = new byte[1024];
        int len;
        while ((len = bais.read(kb)) != -1) {
            os.write(kb, 0, len);
        }
        os.flush();
        os.close();
        bais.close();
    }

    /**
     * Post请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String postAsForm(String url, Map<String, String> params) throws IOException {
        //Post方式
        HttpPost httppost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            if (params != null) {
                List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
                Iterator<String> iter = params.keySet().iterator();

                if (iter != null) {
                    while (iter.hasNext()) {
                        String key = iter.next();
                        nvpList.add(new BasicNameValuePair(key, params.get(key)));
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvpList, Consts.UTF_8);
                    httppost.setEntity(entity);
                }
            }
            response = client.execute(httppost);
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                response.close();
            }
            client.close();
        }
    }

    /**
     * post请求，参数为json格式
     *
     * @param url      目标地址ServerUrl
     * @param params   参数Map<String,String>
     * @param encoding 编码
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String postAsJson(String url, Map<String, String> params, String encoding) throws ParseException, IOException {
        String body = "";
        System.out.println("--->postAsJson请求地址：" + url);
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);//创建post方式请求对象

        //以Json格式装填参数
        String jsonStr = JSON.toJSONString(params);
        StringEntity strEnt = new StringEntity(jsonStr, "utf-8");
        strEnt.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(strEnt); //设置参数到请求对象中

        //设置header信息,指定报文头【Content-type】、【User-Agent】
        //httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行POST请求，采用同步阻塞方式拿到结果,获取结果实体
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);

        response.close();//释放链接

        return body;
    }

    /**
     * Post请求(将返回的流解析为字符串)
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String postStream(String url, Map<String, String> params) throws IOException {
        String encode = "utf-8";
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("Content-Type", "application/octet-stream; charset=" + encode);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            if (params != null) {
                List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
                Iterator<String> iter = params.keySet().iterator();

                if (iter != null) {
                    while (iter.hasNext()) {
                        String key = iter.next();
                        nvpList.add(new BasicNameValuePair(key, params.get(key)));
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvpList, Consts.UTF_8);
                    httppost.setEntity(entity);
                }
            }
            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            UnicodeInputStream uin = new UnicodeInputStream(stream, encode);
            InputStreamReader in = null;
            encode = uin.getEncoding();

            if (encode == null) {
                in = new InputStreamReader(uin);
            } else {
                in = new InputStreamReader(uin, encode);
            }
            BufferedReader reader = new BufferedReader(in);
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            in.close();
            return sb.toString();
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                response.close();
            }
            client.close();
        }
    }


    /**
     * Get请求(将返回的流解析为字符串)
     *
     * @param url
     * @return
     * @throws IOException
     * @throws
     */
    public static String getStream(String url) throws IOException {
        String res = "";
        String encode = "utf-8";
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Content-Type", "application/octet-stream; charset=" + encode);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(httpget);

        try {
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            UnicodeInputStream uin = new UnicodeInputStream(stream, encode);
            InputStreamReader in = null;

            encode = uin.getEncoding();
            if (encode == null) {
                in = new InputStreamReader(uin);
            } else {
                in = new InputStreamReader(uin, encode);
            }
            BufferedReader reader = new BufferedReader(in);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            in.close();

            //结果
            res = sb.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            response.close();
            client.close();
        }

        return res;
    }

    /**
     * 获取Basic Authentication header
     *
     * @param user
     * @param password
     * @return
     */
    private static String getBasicAuthenHeader(String user, String password) {
        String auth = user + ":" + password;
        byte[] bytes = Base64.encodeBase64(auth.getBytes(Charset.forName("utf-8")));
        return "Basic " + new String(bytes);
    }

    @SuppressWarnings("unused")
    private CloseableHttpClient httpsClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        SSLContext ctx = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
            // 信任所有
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(ctx);
        return HttpClients.custom().setSSLSocketFactory(factory).build();
    }


    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }


}
